var express = require('express');
var router = express.Router();
var _ = require('underscore');
var async = require('async');
var site_info =	require("../config").site_info;
var db_essay = require("../dao/essay-dao");
var db_tag = require("../dao/tag-dao");
var db_category = require("../dao/category-dao");
var dateutils = require("../modules/dateutils");

/* GET home page. */
router.get('/', function(req, res, next) {

	var cur_site_info = _.extend({}, site_info, {
        page:{
            title: "essay - " + site_info.page.title,
            name: "essay",
            intro: "Blog",
            intro_desc: "长路漫漫，只因学无止境",
        }
    });

	return res.render('essay', {
		site_info: cur_site_info
	});
});

router.get('/get-essay', function(req, res, next) {
    var condition = {
        findOne: true,
        searchType: 0,
        searchCriteria:{
            id: req.param("id") || 0
        }
    };

    /*
    async.auto({}, function(err, params){});
    findCategory, findTag, findTodo 之间并行
    */
    async.auto({
        findCategory: function(callback){
            db_category.search({}, function(err, categories){
                if (err) {
                    return callback(err, "");
                }
                else{
                    return callback(null, categories);
                }
            });            
        },
        findTag: function(callback){
            db_tag.search({}, function(err, tags){
                if (err) {
                    return callback(err, "");
                }
                else{
                    return callback(null, tags);
                }
            });
        },
        findEssay: function(callback){
            if(condition.searchCriteria.id == 0){
                return callback(null, {
                    id: 0,
                    title: "",
                    content: "",
                    tag_ids: "",
                    category_id: 0,
                    is_star: 0,
                    post_time: dateutils.addMinutes(new Date(), 5).Format("yyyy-MM-dd hh:mm")
                });
            }
            else{
                db_essay.search(condition, function(err, result){
                    if(err){
                        return callback(err, "");
                    }
                    var curEssay = result.result[0];
                    curEssay.post_time = dateutils.addMinutes(new Date(curEssay.post_time), 5).Format("yyyy-MM-dd hh:mm")
                    return callback(null, curEssay);
                });
            }
        }
    }, function(err, params){
        if (err) {
            return next(err);
        }

        var categories = params["findCategory"]==null?[]:params["findCategory"];
        var tags = params["findTag"]==null?[]:params["findTag"];

        return res.json({
            status: site_info.return_type.success,
            essay: params["findEssay"],
            tags: tags,
            categories: categories
        });
    });
});


router.get('/get-essay-list', function(req, res, next) {
    var condition = {
        searchType: 1,
        searchCriteria:{
            status: req.param("status") || ""
        },
        pagingMetaData: {
            pageIndex: req.param("pageIndex") || 0,
            pageSize:  req.param("pageSize") || site_info.page_size
        },
        sortMetaData: req.param("sortMetaData") || []
    };

    db_essay.search(condition, function(err, result){
        if(err){
            next(err);
        }
        //console.log("result:", result);
        var rtn = _.extend({
            status: site_info.return_type.success, 
            result: [],
            total: 0
        }, result);
        //console.log("rtn:", rtn);
        return res.json(rtn);
    });
});

router.post('/operate-essay-submit', function(req, res, next) {
    var essay = {
        id: req.param("id") || 0,
        tags: req.param("tags") || [],
        is_star: req.param("is_star") || 0,
        category_id: req.param("category_id") || 0,
        title: req.param("title") || "",
        content: req.param("content") || "",
        post_time: req.param("post_time") || new Date()
    };
    console.log(essay)

    db_essay.save(essay, function(err, result){
        if(err){
            next(err);  
        }
        
        return res.json({
            status: site_info.return_type.success,
            result:{
                id: result.id
            }
        });
    });
});
module.exports = router;
